package org.zsl.controller.springmvc;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.zsl.model.ResponseMsg;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {


    @RequestMapping("/upload")
    public ResponseMsg upload(MultipartFile photo, HttpSession session) throws IOException {
        ResponseMsg responseMsg = new ResponseMsg();
        /**
         * step1:  获取上传文件信息
         * */
        String fileName = photo.getOriginalFilename();
        System.out.println("fileName:" + fileName);
        String hzname = fileName.substring(fileName.lastIndexOf("."));
        fileName = "test" + "." + hzname;

        /**
         * step2：准备保存文件的文件夹
         * */

        String filePath = session.getServletContext().getRealPath("upload");
        System.out.println("filePath:" + filePath);
        File file = new File(filePath);
        if (!file.exists()) {

            file.mkdir();
        }
        /**
         *  step3: 保存文件
         * */
        String finalPath = filePath + File.separator + fileName;
        System.out.println("finalPath:" + finalPath);
        photo.transferTo(new File(finalPath));
        return responseMsg;

    }


    @RequestMapping("/download/{filename}")
    public void download(@PathVariable("filename") String filename
            , HttpServletRequest request
            , HttpServletResponse response) throws IOException {
        /**
         *  1. 获取文件信息、服务器的文件保存位置，创建输出流
         * */
         filename = filename+"." + "jpg";
         String uploadPath=   request.getSession().getServletContext().getRealPath("/upload");
        System.out.println("uploadPath:" + uploadPath);
        FileInputStream fileInputStream = new FileInputStream(new File(uploadPath,filename));

        /**
         *  2.设置reponse相关内容
         * */

        response.setContentType("text/plain;charset=UTF-8");
        response.setHeader("content-disposition","attachment;flileName="+filename);
        ServletOutputStream servletOutputStream= response.getOutputStream();

        int len;
        byte[] bytes = new byte[1024];

        while (true){

            len = fileInputStream.read(bytes);

            if(len==-1) break;

            servletOutputStream.write(bytes,0,len);
        }


        fileInputStream.close();
        servletOutputStream.close();




    }
}
